package cz.incad.psh.pshassign.server.search;

import cz.incad.psh.pshassign.server.Options;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;

/**
 *
 * @author Alberto Hernandez
 */
public class ProximitySearch {
    public static boolean isNear(String text, String id) {
        try {
            String q = "id:" + 
                    id + " AND \""+text+"\"~" + Options.getInt("assign", "near");
                    //id + "+AND+\""+text.replaceAll(" ", "+")+"\"~" + Options.getInt("assign", "near");
            
            String urlStr = Options.getOption("invenio", "solr") + "/select?wt=json&rows=0&q=" + URLEncoder.encode(q, "UTF-8");
            
            java.net.URL url = new java.net.URL(urlStr);
            
            InputStream is = url.openStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            JSONObject js = new JSONObject(writer.toString());
            return  js.getJSONObject("response").getInt("numFound")>0;
            
        } catch (Exception e) {
            System.out.println("error :\n" + e);
            e.printStackTrace();
            return false;
        }
    }
}
